package com.example.casesys.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.casesys.dto.UserDTO;
import com.example.casesys.dto.WritDTO;
import com.example.casesys.entity.Writ;
import com.example.casesys.mapper.WritMapper;
import com.example.casesys.service.WritService;
import com.example.casesys.utils.FileUtil;
import com.example.casesys.utils.UserHolder;
import com.example.casesys.vo.Result;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

import static com.example.casesys.utils.FileUrlPatterns.FILE_URL_LINUX;

/**
 * @author kongke
 * @description 针对表【tb_writ(文书)】的数据库操作Service实现
 * @createDate 2023-10-13 20:05:46
 */
@Service
public class WritServiceImpl extends ServiceImpl<WritMapper, Writ> implements WritService {

    private static final Integer PAGE_SIZE = 10;

    @Resource
    private FileUtil fileUtil;


    /**
     * 查询文书
     *
     * @param current 页脚
     * @return {@link Result}
     */
    @Override
    public Result getWrits(Integer current, String writType) {
        Page<Writ> page = Page.of(current, PAGE_SIZE);
        WritDTO writDTO = new WritDTO();
//        分页查询
        Page<Writ> writPage = query()
                .eq("writ_type", writType)
                .page(page);
        long total = writPage.getTotal();
        List<Writ> writs = writPage.getRecords();
        if (writs.isEmpty()) {
            return Result.fail().message("没有查询到相关信息！");
        }
        writDTO.setWrits(writs);
        writDTO.setCount(total);
        return Result.ok(writDTO).message("查询成功");
    }

    @Override
    public Result upload(String type, MultipartFile file, HttpSession session) {
        Integer userId = UserHolder.getUser(session).getId();
        Writ writ = new Writ();
        writ.setWritType(type);
        writ.setUserId(userId);
        Map<String, String> resMap = fileUtil.uploadFile(file);
        String url = resMap.get("url");
//        如果url不为空，则说明上传成功
        if (url != null) {
//            切割返回的字符串，分离出serName , cliName
            String[] splits = url.split("/");
            int length = splits.length;
            writ.setWritNameSer(splits[length - 2]);
            writ.setWritNameCli(splits[length - 1]);
            save(writ);
            return Result.ok(url).message("文件上传成功！");
        }
//        url为空则上传失败，返回fail中的错误信息
        return Result.fail().message(resMap.get("fail"));
    }

    @Override
    public ResponseEntity<byte[]> download(String serName) {
//        查找数据库中是否存在该文件
        Writ writ = query().eq("writ_name_ser", serName).one();
        if (writ != null) {
//        存在则开始下载(下载失败则返回null)
            return fileUtil.downloadFile(serName);
        }
//        否则返回空
        return null;
    }

    /**
     * 删除文书
     *
     * @return {@link Result}
     */
    @Override
    public Result delWrit(Integer writId, HttpSession session) {
//      只有本人或者管理员能删除
        UserDTO userDTO = UserHolder.getUser(session);
        Writ writ = query().eq("id", writId).one();
        int userId = userDTO.getId();
        int authId = writ.getUserId();
        String writNameSer = writ.getWritNameSer();
        Integer accType = userDTO.getAccType();

        if (userId != authId && accType < 2) {
//            没有权限删除
            return Result.fail().message("没有权限删除");
        }

        boolean rm = removeById(writId);
        if (rm) {
//            删除文书文件
            fileUtil.delFile(FILE_URL_LINUX + writNameSer);
            return Result.ok().message("删除成功！");
        }
        return Result.fail().message("删除失败");
    }

}




